import { _decorator, Component, sp, Node, instantiate, tween, Vec3 } from 'cc';
import { StateDefine } from '../actor/StateDefine';
import { FortressManager } from './FortressManager';
import { FortressBase } from './FortressBase';
const { ccclass, property } = _decorator;

@ccclass('Louis')
export class Louis extends Component {
    @property(sp.Skeleton)
    skeleton: sp.Skeleton = null!;
    private curState: StateDefine = StateDefine.idle;

    // 子弹预制体
    @property(Node)
    projectilePrefab: Node = null!;

    // 子弹发射口
    @property(Node)
    firePoint: Node = null!;

    /** 攻击间隔（秒） */
    @property({ tooltip: '攻击间隔（秒）' })
    atkInterval: number = 1.0;
    private _lastAtkTime: number = 0;

    public targetPoint: Vec3 = Vec3.ZERO;

    start() {

    }
    /**
     * 触发攻击（带间隔限制）
     */
    public tryAttack(atkTarget: Node) {
        if (atkTarget == null) {
            this.changeState(StateDefine.idle, true);
            return;
        }

        const now = Date.now() / 1000;
        if (now - this._lastAtkTime < this.atkInterval) return;
        this._lastAtkTime = now;
        this.changeState(StateDefine.atk, false, () => {
            this.changeState(StateDefine.idle, true);
        });
    }

    private onFire() {
        const projectile = instantiate(this.projectilePrefab);
        projectile.active = true;
        projectile.setParent(this.node);
        projectile.setPosition(this.firePoint.getPosition());

        // 计算方向并设置旋转
        const startPos = projectile.worldPosition.clone();
        const endPos = this.targetPoint.clone();
        const dir = endPos.clone().subtract(startPos);
        const angle = Math.atan2(dir.y, dir.x) * 180 / Math.PI;
        projectile.angle = angle;

        // 第一段：A到B，0.5s
        const duration1 = 0.5;
        // 计算B点到C点（B沿dir方向延长3倍距离）
        const distAB = dir.length();
        const dirNorm = dir.normalize();
        const C = endPos.clone().add(dirNorm.multiplyScalar(distAB * 3));
        const duration2 = duration1 * 3; // 1.5s

        tween(projectile)
            .to(duration1, { worldPosition: endPos })
            .to(duration2, { worldPosition: C })
            .call(() => {
                projectile.destroy();
            })
            .start();
    }

    /**
     * 状态切换，支持动画播放完成回调
     * @param newState 新状态
     * @param wrapMode 1:播放一次 2:循环播放
     * @param onFinished 动画播放完成回调
     */
    private _isPlayingAtk: boolean = false;
    private changeState(newState: StateDefine, loop: boolean = true, onFinished?: () => void) {
        if (this.curState === StateDefine.die) return;
        // 只有攻击动画播放完成后才允许切换到idle
        if (this._isPlayingAtk && newState === StateDefine.idle) return;

        if (this.curState === newState) return;
        this.curState = newState;
        let animName = '';
        switch (newState) {
            case StateDefine.idle:
                animName = 'idel';
                break;
            case StateDefine.atk:
                animName = 'skill';
                break;
        }


        if (this.skeleton && animName) {
            this.skeleton.setAnimation(0, animName, loop);
            if (newState === StateDefine.atk) {
                this._isPlayingAtk = true;
                this.onFire();
                this.skeleton.setCompleteListener(() => {
                    this.skeleton.setCompleteListener(null);
                    this._isPlayingAtk = false;
                    if (onFinished) onFinished();
                });
            } else {
                this.skeleton.setCompleteListener(null);
                if (onFinished) onFinished();
            }
        }
    }
}